package com.nie.orderfood.service.impl;

import com.nie.orderfood.DTO.CartDTO;
import com.nie.orderfood.DTO.OrderMasterDTO;
import com.nie.orderfood.Utils.GenIdUtil;
import com.nie.orderfood.convertor.OrderMaster2OrderMasterDTOConvertor;
import com.nie.orderfood.entity.OrderDetail;
import com.nie.orderfood.entity.OrderMaster;
import com.nie.orderfood.entity.ProductInfo;
import com.nie.orderfood.enums.OrderStatusEnum;
import com.nie.orderfood.enums.PayStatusEnum;
import com.nie.orderfood.enums.ResultEnum;
import com.nie.orderfood.exception.SellException;
import com.nie.orderfood.repository.OrderDetailRepository;
import com.nie.orderfood.repository.OrderMasterRepository;
import com.nie.orderfood.service.OrderService;
import com.nie.orderfood.service.ProductInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @program: orderfood
 *
 * @description: 订单类service实现类
 * @author: NieMiao
 * @create: 2018-10-10 11:17
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Override
    public OrderMasterDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterRepository.findById(orderId).get();
        if (orderMaster == null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST_ERROR);
        }
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST_ERROR);
        }
        OrderMasterDTO orderMasterDTO = new OrderMasterDTO();
        BeanUtils.copyProperties(orderMaster,orderMasterDTO);
        orderMasterDTO.setOrderDetailList(orderDetailList);
        return orderMasterDTO;
    }

    @Override
    public Page<OrderMasterDTO> findList(String opendId, Pageable pageable) {
        Page<OrderMaster> orderMasters = orderMasterRepository.findByBuyerOpenid(opendId, pageable);

        List<OrderMasterDTO> convert = OrderMaster2OrderMasterDTOConvertor.convert(orderMasters.getContent());

        return new PageImpl<OrderMasterDTO>(convert,pageable,orderMasters.getTotalElements());
    }

    @Override
    @Transactional
    public OrderMasterDTO createOrder(OrderMasterDTO orderMasterDTO) {
        String orderId = GenIdUtil.genOrderMasterId();
        BigDecimal amount = new BigDecimal(BigInteger.ZERO);
        //1.查询商品（数量，价格）
        for (OrderDetail orderDetail:orderMasterDTO.getOrderDetailList()) {
            ProductInfo product = productInfoService.findByProductId(orderDetail.getProductId());
            if (product == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //2.计算总价
            amount = product.getProductPrice()
                    .multiply(new BigDecimal(orderDetail
                            .getProductQuantity())).add(amount);
            orderDetail.setDetailId(GenIdUtil.genOrderMasterId());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(product,orderDetail);
            orderDetailRepository.save(orderDetail);
        }

        //3.计入数据库（订单表，订单详情表）
        OrderMaster orderMaster = new OrderMaster();
        orderMasterDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderMasterDTO,orderMaster);
        orderMaster.setOrderAmount(amount);
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMasterRepository.save(orderMaster);
        //4.扣库存
        List<CartDTO> cartDTOList = orderMasterDTO.getOrderDetailList()
                .stream().map(e->
                new CartDTO(e.getProductId(),e.getProductQuantity())).collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);
        return orderMasterDTO;
    }

    @Override
    @Transactional
    public OrderMasterDTO cancelOrder(OrderMasterDTO orderMasterDTO) {
        OrderMaster orderMaster = new OrderMaster();
        //判断订单状态
        if (!orderMasterDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderMasterDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderMasterDTO,orderMaster);
        OrderMaster save = orderMasterRepository.save(orderMaster);
        if (save == null) {
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        //加库存
        if (orderMasterDTO.getOrderDetailList().isEmpty()) {
            throw new SellException(ResultEnum.ORDER_EMPTY_ERROR);
        }
        List<CartDTO> cartDTOList  = orderMasterDTO.getOrderDetailList().stream().map(e ->
                new CartDTO(e.getProductId(),e.getProductQuantity())).collect(Collectors.toList());
        productInfoService.increaseStock(cartDTOList);
        //退款
        if (orderMasterDTO.getPayStatus().equals(PayStatusEnum.SUCCESS)) {
            //TODO
        }
        return orderMasterDTO;
    }

    @Override
    @Transactional
    public OrderMasterDTO finishOrder(OrderMasterDTO orderMasterDTO) {
        //判断订单状态
        if (!orderMasterDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderMasterDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderMasterDTO,orderMaster);
        OrderMaster orderMaster1 = orderMasterRepository.save(orderMaster);
        if (orderMaster1 == null) {
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        return orderMasterDTO;
    }

    @Override
    @Transactional
    public OrderMasterDTO paidOrder(OrderMasterDTO orderMasterDTO) {
        //判断订单状态
        if (!orderMasterDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //判断订单支付状态
        if (!orderMasterDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }
        //修改订单状态
        orderMasterDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderMasterDTO,orderMaster);
        OrderMaster orderMaster1 = orderMasterRepository.save(orderMaster);
        if (orderMaster1 == null) {
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        return orderMasterDTO;
    }
}
